<template>
  <div>
    <!-- 添加面包屑与卡片视图 -->
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleslist" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item,i1) in scope.row.children"
              :key="item.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="delRights( scope.row,item.id )">
                  {{ item.authName }}
                  <i class="el-icon-caret-right"></i>
                </el-tag>
              </el-col>
              <!-- 二级与三级 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2,i2) in item.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag closable @close="delRights( scope.row,item2.id )" type="success">
                      {{ item2.authName }}
                      <i class="el-icon-caret-right"></i>
                    </el-tag>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="delRights( scope.row,item3.id )"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="warning" @click="settingRights(scope.row)" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限分配的弹窗 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="50%">
      <el-tree 
      show-checkbox 
      default-expand-all 
      :data="rightTreeList" 
      :props="treeProps"
      node-key="id"
      :default-checked-keys = "checkedArr"
      ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      roleslist: [],
      treeProps:{
        label:'authName',
        children:'children'
      },
      roleId:'',
      checkedArr:[],
      rightTreeList: [] // 权限的树状结构
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.roleslist = res.data;
      console.log(this.roleslist);
      this.$message.success("获取数据成功");
    },
    async delRights(roleInfo, rightId) {
      // 要弹出message-box
      console.log(this.roleId,roleInfo);
      const comfirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (comfirmResult == "confirm") {
        // roles/:roleId/rights/:rightId
        const { data: res } = await this.$http.delete(
          `roles/${roleInfo.id}/rights/${rightId}`
        );

        if (res.meta.status == 200) {
          this.$message.success("删除用户成功！");
          roleInfo.children = res.data;
        }
      } else {
        return this.$message.error("取消删除");
      }
    },
    async settingRights(row) {
      // 获取权限列表数据
      // 在弹窗打开的时候 要记录当前的角色的id 
      // 为了提交修改的权限
      this.roleId = row.id
      const { data:res } = await this.$http.get("rights/tree")
      if(res.meta.status == 200){
        this.$message.success('获取列表成功')
        this.rightTreeList = res.data
        this.getCheckedArr( row,this.checkedArr)
        // :default-checked-keys 利用这个属性去绑定 记录角色三级权限的数组
        this.dialogVisible = true;
      }else{
        this.$message.error('获取权限列表失败')
      }
      
    },

    getCheckedArr(node,arr){  // node是当前这行的角色对象
        // 找到的是node下面的三级权限 node就是当前这一行的角色信息
        // 设置递归的跳出条件
        if(!node.children){
          return arr.push(node.id)
        }
        // 递归的具体逻辑
        node.children.forEach( item => this.getCheckedArr(item,arr) )
    },
    async editRoleRights(){
       let rids = [
         ...this.$refs.treeRef.getCheckedKeys(),
         ...this.$refs.treeRef.getHalfCheckedKeys()
       ]
       rids = rids.join(',')
       const { data:res } = await this.$http.post(`roles/${ this.roleId }/rights`,{ 'rids':rids })
       if(res.meta.status != 200){
          this.$message.error('修改权限失败！')
       }else{
         this.$message.success('操作成功')
         this.getRolesList();
         this.dialogVisible = false;
       }
    } 
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>